const fs = require('fs-extra');
const path = require('path');
const logger = require('../utils/logger');
const PathUtils = require('../utils/pathUtils');

class HistoryService {
  constructor() {
    this.historyFile = PathUtils.join(PathUtils.getDataDir(), 'deploy-history.json');
    this.ensureHistoryFile();
  }

  async ensureHistoryFile() {
    try {
      await fs.ensureDir(PathUtils.dirname(this.historyFile));
      if (!(await fs.pathExists(this.historyFile))) {
        await fs.writeJson(this.historyFile, []);
      }
    } catch (error) {
      logger.error('初始化历史文件失败:', error);
    }
  }

  async getHistory(limit = 50, offset = 0) {
    try {
      const history = await fs.readJson(this.historyFile);
      const sortedHistory = history.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
      return {
        total: sortedHistory.length,
        data: sortedHistory.slice(offset, offset + limit)
      };
    } catch (error) {
      logger.error('读取历史记录失败:', error);
      return { total: 0, data: [] };
    }
  }

  async getRecord(deployId) {
    try {
      const history = await fs.readJson(this.historyFile);
      return history.find(record => record.id === deployId);
    } catch (error) {
      logger.error('获取部署记录失败:', error);
      return null;
    }
  }

  async addRecord(record) {
    try {
      await this.ensureHistoryFile();
      const history = await fs.readJson(this.historyFile);
      
      // 添加默认字段
      const newRecord = {
        ...record,
        logs: record.logs || [],
        createdAt: record.createdAt || new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      
      history.push(newRecord);
      
      // 保持最多1000条记录
      if (history.length > 1000) {
        history.splice(0, history.length - 1000);
      }
      
      await fs.writeJson(this.historyFile, history, { spaces: 2 });
      return newRecord;
    } catch (error) {
      logger.error('添加部署记录失败:', error);
      throw error;
    }
  }

  async updateRecord(deployId, updates) {
    try {
      const history = await fs.readJson(this.historyFile);
      const recordIndex = history.findIndex(record => record.id === deployId);
      
      if (recordIndex === -1) {
        throw new Error(`部署记录不存在: ${deployId}`);
      }
      
      history[recordIndex] = {
        ...history[recordIndex],
        ...updates,
        updatedAt: new Date().toISOString()
      };
      
      await fs.writeJson(this.historyFile, history, { spaces: 2 });
      return history[recordIndex];
    } catch (error) {
      logger.error('更新部署记录失败:', error);
      throw error;
    }
  }

  async addLog(deployId, logEntry) {
    try {
      const history = await fs.readJson(this.historyFile);
      const recordIndex = history.findIndex(record => record.id === deployId);
      
      if (recordIndex === -1) {
        throw new Error(`部署记录不存在: ${deployId}`);
      }
      
      if (!history[recordIndex].logs) {
        history[recordIndex].logs = [];
      }
      
      history[recordIndex].logs.push(logEntry);
      history[recordIndex].updatedAt = new Date().toISOString();
      
      await fs.writeJson(this.historyFile, history, { spaces: 2 });
      return logEntry;
    } catch (error) {
      logger.error('添加部署日志失败:', error);
      throw error;
    }
  }

  async deleteRecord(deployId) {
    try {
      const history = await fs.readJson(this.historyFile);
      const filteredHistory = history.filter(record => record.id !== deployId);
      
      if (filteredHistory.length === history.length) {
        throw new Error(`部署记录不存在: ${deployId}`);
      }
      
      await fs.writeJson(this.historyFile, filteredHistory, { spaces: 2 });
      return true;
    } catch (error) {
      logger.error('删除部署记录失败:', error);
      throw error;
    }
  }

  async clearHistory() {
    try {
      await fs.writeJson(this.historyFile, []);
      return true;
    } catch (error) {
      logger.error('清空历史记录失败:', error);
      throw error;
    }
  }

  async getStatistics() {
    try {
      const history = await fs.readJson(this.historyFile);
      
      const stats = {
        total: history.length,
        success: history.filter(r => r.status === 'success').length,
        failed: history.filter(r => r.status === 'failed').length,
        running: history.filter(r => r.status === 'running').length,
        pending: history.filter(r => r.status === 'pending').length
      };
      
      // 最近7天的部署统计
      const sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
      
      const recentDeploys = history.filter(r => 
        new Date(r.timestamp) > sevenDaysAgo
      );
      
      stats.recent = {
        total: recentDeploys.length,
        success: recentDeploys.filter(r => r.status === 'success').length,
        failed: recentDeploys.filter(r => r.status === 'failed').length
      };
      
      return stats;
    } catch (error) {
      logger.error('获取统计信息失败:', error);
      return {
        total: 0,
        success: 0,
        failed: 0,
        running: 0,
        pending: 0,
        recent: { total: 0, success: 0, failed: 0 }
      };
    }
  }
}

module.exports = new HistoryService();